package com.insight.common.mq;

import com.yuanqiao.insight.common.util.common.RedisStreamUtil;
import com.yuanqiao.insight.common.util.common.RedisUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import com.insight.common.mq.stream.RedisMqStream;
import com.insight.common.mq.stream.Streams;
import com.insight.common.mq.utils.MachineCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author JinPengDong
 * @date 2022/9/16
 */
@Slf4j
@Configuration
public class RedisMqInit {

    @Getter
    private static RedisStreamUtil redisStreamUtil;
    @Getter
    private static RedisUtils redisUtils;
    @Getter
    private static String GROUP;
    private static String CONSUMER;
    @Getter
    private static Integer PORT;
    @Getter
    private static RedisMq redisMq;

    public static final Map<String, Boolean> isSubscribe = new HashMap<>();

    @Value("${spring.redis.stream.group}")
    public void setGroup(String group) {
        GROUP = group;
    }

    @Value("${spring.redis.stream.consumer}")
    public void setConsumer(String consumer) {
        CONSUMER = consumer;
    }

    @Value("${server.port}")
    public void setPort(Integer port) {
        PORT = port;
    }

    public static String getCONSUMER() {
        final String lowerCase = CONSUMER.toLowerCase(Locale.ROOT);
        if (lowerCase.equals("auto")) {
            CONSUMER = String.format("%s-%s-%s", getGROUP(), MachineCodeUtil.getMachineCode(), getPORT());
        }
        return CONSUMER;
    }

    @Autowired
    public void setRedisStreamUtil(RedisStreamUtil redisStreamUtil) {
        RedisMqInit.redisStreamUtil = redisStreamUtil;
    }

    @Autowired
    public void setRedisUtils(RedisUtils redisUtils) {
        RedisMqInit.redisUtils = redisUtils;
    }

    @Autowired
    public void setRedisMq(RedisMq redisMq) {
        RedisMqInit.redisMq = redisMq;
    }

    @PostConstruct
    public void initMq() {
        Arrays.stream(Streams.values()).forEach(item -> {
            final RedisMqStream redisMqStream = item.getValue();
            final String key = redisMqStream.getName();
            redisStreamUtil.createStream(key, redisMqStream.getGroup());
            isSubscribe.put(key, true);
        });
    }

    public static void main(String[] args) {
        System.out.println(MachineCodeUtil.getMachineCode());
    }
}
